<template>
    <div class="p-grid crud-demo">
        <div class="p-col-12">
            <!--面包屑-->
            <div  style="padding-bottom: 0.95rem;">
                <Breadcrumb :home="home" :model="crumbs"/>
            </div>
        </div>

        <div class="p-col-12 p-md-6">
            <div class="card p-fluid">
                <h3> {{edit_title}}</h3>
                <h5>基本信息</h5>

                <div class="p-formgrid p-grid">
                    <div class="p-field p-col">
                        <label for="">产品分类</label>
                        <Dropdown v-model="ClassifySelectedValue" :options="ClassifySelected" optionLabel="name" placeholder="选择" />

                    </div>
                    <div class="p-field p-col">
                        <label for="">卡种(默认自身)</label>
                        <Dropdown v-model="PidSelectedValue" :options="PidSelected" optionLabel="name" placeholder="选择" />

                    </div>
                    <div class="p-field p-col">
                        <label for="">对接模型</label>
                        <Dropdown v-model="AccessSelectedValue" :options="AccessSelected" optionLabel="name" placeholder="选择" />

                    </div>
                </div>
                <div class="p-field" v-show="PidSelectedValue === null">
                    <label for="age1">产品卡种</label>
                    <InputText  id="kind_name" v-model="kind_name" type="text"/>
                </div>

                <div class="p-field">
                    <label for="name">产品名称</label>
                    <InputText id="name" v-model="name"  type="text" />
                </div>
                <div class="p-field">
                    <label for="titile">标题</label>
                    <InputText id="titile" v-model="titile"  type="text" />
                </div>
                <div class="p-field">
                    <label for="age1">首页图片</label>

                    <div class="p-col-4 p-md-3">
                        <Button label="上传" icon="pi pi-cloud-upload" iconPos="left" @click="choiceAddImg"/>
                    </div>
                    <input ref="filElem2" class="input-plupload" @change='add_make_img_change'
                           type="file">
                    <div style="position: relative; width: 150px; margin: 0 auto;">
                        <img v-show="icon !== null"  width="150px" :src="icon" alt="首图">
                    </div>
                </div>

                <h5>产品介绍页</h5>
                <Editor v-model="first_desc" editorStyle="height: 500px"/>

            </div>
        </div>

        <div class="p-col-12 p-md-6">
            <div class="card p-fluid">
                <h5>流量配置</h5>

                <div class="p-formgrid p-grid">
                    <div class="p-field p-col">
                        <label for="price">售价(元)</label>
                        <InputText id="price" v-model="price"  type="text" />
                    </div>
                    <div class="p-field p-col">
                        <label for="stocks">库存</label>
                        <InputNumber id="minmax-buttons" v-model="stocks" mode="decimal" showButtons :min="0" :max="1000000" />
                    </div>
                    <div class="p-field p-col">
                        <label for="sales">显示销量</label>
                        <InputNumber id="minmax-buttons" v-model="sales" mode="decimal" showButtons :min="0" :max="1000000000" />
                    </div>
                    <div class="p-field p-col">
                        <label for="sort">排序</label>
                        <InputNumber id="minmax-buttons" v-model="sort" mode="decimal" showButtons :min="0" :max="1000000" />
                    </div>
                </div>

                <div class="p-formgrid p-grid">
                    <div class="p-field p-col">
                        <label for="recommend">推荐星级</label>
                        <Rating v-model="recommend"/>
                    </div>
                    <div class="p-field p-col">
                        <label for="status">上架状态</label>
                        <div class="p-field p-col">
                        <InputSwitch v-model="status" />
                        </div>
                    </div>
                </div>
            </div>

            <div class="card">
                <h5>发货禁区</h5>
                <div class="p-field p-fluid">
                    <label for="username">支持多选</label>
                    <MultiSelect v-model="PenaltySelectedsValue" :options="PenaltySelecteds" optionLabel="brand" placeholder="选择" :filter="true"/>
                    <small>添加到禁区的地区会拦截下单。</small>
                </div>
            </div>

            <div class="card">
                <h5>佣金规则</h5>
                <div class="p-field p-fluid">
                    <label for="username">支持多选</label>
                    <MultiSelect v-model="CommissionSelectedsValue" :options="CommissionSelecteds" optionLabel="brand" placeholder="选择" :filter="true"/>
                    <small>达到返佣规则条件时，系统会将佣金划入合伙人账户，并做相应的明细记录。</small>
                </div>

                <Button label="提交" @click="submit"/>&nbsp;
                <Button label="返回" @click="back" class="p-button-secondary" />
            </div>

        </div>

        </div>

</template>

<script>
    import TableService from '@/api/TableService';
    import UploadService from '@/api/UploadService';
    export default {
        data() {
            return {
                data:null,
                ClassifySelected:null,
                ClassifySelectedValue:null,
                PidSelected:null,
                PidSelectedValue:null,
                AccessSelected:null,
                AccessSelectedValue:null,
                PenaltySelecteds:null,
                PenaltySelectedsValue:null,
                CommissionSelecteds:null,
                CommissionSelectedsValue:null,
                kind_name:null,
                sort:null,
                price:null,
                name:null,
                titile:null,
                icon:null,
                first_desc:null,
                stocks:null,
                sales:null,
                recommend:null,
                status:true,
                edit_title:'添加产品',
                home: {label: '控制台', icon: 'pi pi-home', to: '/'}, //面包屑公共导航
                crumbs: [ //面包屑
                ],
            }
        },
        TableService: null,
        created() {
            this.TableService = new TableService();
            //获取当前路由名称
            for (let i = 0; i < this.$router.options.routes[1].children.length ; i++){
                if(this.$router.options.routes[1].children[i].path === this.$route.path){
                    this.crumbs = [
                        {label: '产品管理', },
                        {label: this.$router.options.routes[1].children[i].meta.title},
                    ];
                }
            }
        },
        watch: {
            //避免下拉框属性加载慢导致未选中
            CommissionSelecteds(val)
            {
                if(this.CommissionSelectedsValue === null && this.data !== null){
                   this.CommissionSelectedsValue = this.checkeds(val, this.data.data.commission);
                }
            },
            PenaltySelecteds(val)
            {
                if(this.PenaltySelectedsValue === null && this.data !== null){
                    this.PenaltySelectedsValue = this.checkeds(val, this.data.data.penalty);
                }
            },
            ClassifySelected(val)
            {
                if(this.ClassifySelectedValue === null && this.data !== null){
                    this.ClassifySelectedValue = this.checked(val, this.data.data.cid);
                }
            },
            PidSelected(val)
            {
                if(this.PidSelectedValue === null && this.data !== null){
                    this.PidSelectedValue = this.checked(val, this.data.data.pid);
                }
            },
            AccessSelected(val)
            {
                if(this.AccessSelectedValue === null && this.data !== null){
                    this.AccessSelectedValue = this.checked(val, this.data.data.access);
                }
            },
        },
        mounted() {
            this.UploadService = new UploadService();
            this.getClassifySelected();
            this.getPidSelected();
            this.getAccessSelected();
            this.getPenaltySelecteds();
            this.getCommissionSelecteds();
            this.getInfo();
        },
        methods: {
            submit()
            {
                let method = (Object.keys(this.$route.query).length < 1) ? '/add' : '/edit';
                let params = {
                    kind_name:this.kind_name,
                    sort:this.sort,
                    price:this.price,
                    name:this.name,
                    titile:this.titile,
                    icon:this.icon,
                    first_desc:this.first_desc,
                    stocks:this.stocks,
                    sales: this.sales,
                    recommend:this.recommend,
                    status:this.status,
                    cid:this.getCheckedValue(this.ClassifySelectedValue),
                    pid:this.getCheckedValue(this.PidSelectedValue),
                    access:this.getCheckedValue(this.AccessSelectedValue),
                    penalty:this.getCheckedsValue(this.PenaltySelectedsValue),
                    commission:this.getCheckedsValue(this.CommissionSelectedsValue),
                };

                params = Object.assign(params,this.$route.query);
                this.TableService.post('/product_sale'+method, params).then(data => {
                    if (data === undefined) {return;}
                    if (typeof (data) === 'object' && data.code !== 20000) {return;}
                    this.$toast.add({severity: 'success', summary: '提示', detail: data.msg, life: 3000});

                    setTimeout(() =>{
                        this.back();
                    },1500);
                });
            },
            back()
            {
                this.$router.go(-1);//返回上一层
            },
            getCheckedValue(value, value_name='code')   //获取单选框的值
            {
                if(value === null){
                    return null;
                }
                try {
                    return value.[value_name];
                }catch (e) {
                    return null;
                }
            },
            checked(select, value, value_name='code')   //选中单选
            {
                if(select === null){
                    return null;
                }
                let index = select.indexOf(select.filter(d=>Number(d.[value_name]) === Number(value))[0]);
                try {
                    if(index !== -1){
                        return select[index];
                    }
                }catch (e) {
                    return null;
                }
            },
            getCheckedsValue(values, value_name='value')   //获取多选框的值
            {
                if(values === null){
                    return null;
                }
                let vals = '';
                for(let key in values){
                    if(vals !== ''){
                        vals = vals+',';
                    }
                    vals = vals+values[key].[value_name];
                }
                return vals;
            },
            checkeds(select, values, value_name='value')   //选中多选
            {
                if(select === null){
                    return null;
                }
                let final = null;
                let vals = values.split(",");
                for(let i=0;i<vals.length;i++)
                {
                    let index = select.indexOf(select.filter(d=>Number(d.[value_name]) === Number(vals[i]))[0]);
                    if(index !== -1){
                        if (final === null){
                            final = [];
                        }
                        final.push(select[index]);
                    }
                }
                return final;
            },
            getInfo()
            {
                if(Object.keys(this.$route.query).length < 1){
                    return;
                }
                this.TableService.get('/product_sale/edit', this.$route.query).then(data => {
                    if (data === undefined) {return;}
                    if (typeof (data) === 'object' && data.code !== 20000) {return;}
                    this.data = data;
                    this.edit_title = '正在编辑：#'+data.data.id+' '+data.data.name;
                    this.kind_name = data.data.kind_name;
                    this.sort = Number(data.data.sort);
                    this.price = data.data.price==='免费' ? 0 : Number(data.data.price);
                    this.name = data.data.name;
                    this.titile = data.data.titile;
                    this.icon = data.data.icon;
                    this.first_desc = data.data.first_desc;
                    this.stocks = Number(data.data.stocks);
                    this.sales = Number(data.data.sales);
                    this.recommend = Number(data.data.recommend);
                    this.status = data.data.status;

                    //下拉框选中
                    this.ClassifySelectedValue = this.checked(this.ClassifySelected, data.data.cid); //产品分类
                    this.PidSelectedValue =  data.data.pid> 0 ? this.checked(this.PidSelected, data.data.pid) : null; //卡种分类
                    this.AccessSelectedValue = this.checked(this.AccessSelected, data.data.access); //模型分类
                    //多选
                    this.PenaltySelectedsValue = this.checkeds(this.PenaltySelecteds, data.data.penalty); //产品分类
                    this.CommissionSelectedsValue = this.checkeds(this.CommissionSelecteds, data.data.commission); //产品分类

                });
            },
            getClassifySelected()  //获取产品分类
            {
                this.TableService.post('/product_classify/selected', {}).then(data => {
                    if (data === undefined) {return;}
                    if (typeof (data) === 'object' && data.code !== 20000) {return;}
                    this.ClassifySelected = data.data;
                });
            },
            getPidSelected()
            {
                this.TableService.post('/product_sale/selected_pid_name', {}).then(data => {
                    if (data === undefined) {return;}
                    if (typeof (data) === 'object' && data.code !== 20000) {return;}
                    this.PidSelected = data.data;
                });
            },
            getAccessSelected()
            {
                this.TableService.post('/product_access/selected', {}).then(data => {
                    if (data === undefined) {return;}
                    if (typeof (data) === 'object' && data.code !== 20000) {return;}
                    this.AccessSelected = data.data;
                });
            },
            getPenaltySelecteds()
            {
                this.TableService.post('/product_penalty/selecteds', {}).then(data => {
                    if (data === undefined) {return;}
                    if (typeof (data) === 'object' && data.code !== 20000) {return;}
                    this.PenaltySelecteds = data.data;
                });
            },
            getCommissionSelecteds()
            {
                this.TableService.post('/product_commission/selecteds', {}).then(data => {
                    if (data === undefined) {return;}
                    if (typeof (data) === 'object' && data.code !== 20000) {return;}
                    this.CommissionSelecteds = data.data;
                });
            },
            choiceAddImg() {
                this.$refs.filElem2.dispatchEvent(new MouseEvent('click'))
            },
            add_make_img_change(event) {
                let check = this.UploadService.check(event);
                if (check.code !== 20000) {
                    this.$toast.add({severity: 'info', summary: '提示', detail: check.msg, life: 3000});
                    return;
                }
                this.UploadService.post(check.data).then(data => {
                    console.log('data:' + JSON.stringify(data));
                    if (data.code !== 20000) {
                        this.$toast.add({severity: 'info', summary: '提示', detail: data.msg, life: 3000});
                        return;
                    }
                    this.icon = data.data[0].full_path;
                });
            },
        },
        beforeDestroy() {

        }
    }
</script>

<style>
    .input-plupload {
        display: none;
    }
</style>